package sindconsole.misc.webapp.controller;

import common.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sindconsole.misc.bean.Dict;
import sindconsole.misc.bean.DictItem;
import sindconsole.misc.service.DictService;

@Slf4j
@RestController
@RequestMapping("/api/misc")
@RequiresPermissions("dict:all")
public class DictController {

    @Autowired
    DictService dictService;

    @GetMapping("/dicts")
    public Object listDicts() {
        return dictService.findAllDicts();
    }

    @PostMapping("/dicts")
    public Object createDict(@RequestBody Dict dict) {
        dictService.createDict(dict);
        return dict;
    }

    @PostMapping("/dicts/{id}")
    public Object updateDict(@PathVariable("id") long id,
                             @RequestBody Dict dict) {
        if(id != dict.getId()) throw new BadRequestException();
        return dictService.updateDict(dict);
    }

    @PostMapping("/dicts/{id}|remove")
    public Object removeDict(@PathVariable("id") long id) {
        return dictService.deleteDict(id);
    }

    @GetMapping("/dicts/{dictId}/items")
    public Object treeDictItems(@PathVariable("dictId") long dictId) {
        return dictService.treeDictItems(dictId);
    }

    @PostMapping("/dicts/{dictId}/items")
    public Object createDictItem(@PathVariable("dictId") long dictId,
                                 @RequestBody DictItem dictItem) {
        if(dictId != dictItem.getDictId()) throw new BadRequestException();
        dictService.createDictItem(dictItem);
        return dictItem;
    }

    @PostMapping("/dicts/{dictId}/items/{itemId}")
    public Object updateDictItem(@PathVariable("dictId") long dictId,
                                 @PathVariable("itemId") long itemId,
                                 @RequestBody DictItem dictItem) {
        if(dictId != dictItem.getDictId() && itemId != dictItem.getId()) throw new BadRequestException();
        return dictService.updateDictItem(dictItem);
    }

    @PostMapping("/dicts/{dictId}/items/{itemId}|remove")
    public Object removeDictItem(@PathVariable("dictId") long dictId,
                                 @PathVariable("itemId") long itemId) {
        return dictService.deleteDictItem(dictId, itemId);
    }

    @PostMapping("/dicts/{dictId}/items/{itemId}|relink")
    public Object relinkDictItem(@PathVariable("dictId") long dictId,
                                 @PathVariable("itemId") long itemId,
                                 @RequestParam("parentId") long parentId) {
        return dictService.relinkDictItems(dictId, parentId, itemId);
    }

}
